package com.shidaimanong.controller;

import com.shidaimanong.entity.Blog;
import com.shidaimanong.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 学编程，关注：十代码农
 * 抖音、快手、B站、西瓜视频、今日头条
 */
@Controller
@RequestMapping("/blog")
public class BlogWebController {

    @Autowired
    private BlogService blogService;

    @GetMapping("/index")
    public String index() {
        return "index"; //当浏览器输入/index时，会返回 /templates/index时.html页面
    }

    @GetMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView("blogList");
        modelAndView.addObject("blogs", blogService.queryAll());
        return modelAndView;
    }

    @GetMapping("/addBlogPage")
    public ModelAndView addBlogPage() {
        ModelAndView modelAndView = new ModelAndView("addBlogPage");
        return modelAndView;
    }

    @PostMapping(value = "addBlog")
    public ModelAndView addBlog(String title, String content) {
        blogService.add(title, content);
        return new ModelAndView("redirect:/blog/list");
    }

    @GetMapping(value = "modifyBlogPage/{id}")
    public ModelAndView modifyBlogPage(@PathVariable int id) {
        Blog blog = blogService.query(id);
        ModelAndView modelAndView = new ModelAndView("modifyBlogPage");
        modelAndView.addObject("blog", blog);
        return modelAndView;
    }

    @PostMapping(value = "modifyBlog")
    public ModelAndView modifyBlog(int id, String title, String content) {
        blogService.modify(id, title, content);
        return new ModelAndView("redirect:/blog/list");
    }
}